#include "barreldist.h"
#include<QDebug>
#include<QtCore/qmath.h>

namespace krm{


BarrelDist::BarrelDist(){

}
QPixmap* BarrelDist::distortImage(int i,QPixmap* ppixmap){

  QImage originalImage = ppixmap->toImage();
  QImage warpedImage = originalImage.copy();
  const QRgb* oldPixels = (QRgb*)originalImage.bits();
  QRgb* newPixels = (QRgb*)warpedImage.bits();

  const int imgWidth = warpedImage.width();
  const int imgHeight = warpedImage.height();
  const int halfWidth = imgWidth / 2;
  const int halfHeight = imgHeight / 2;

  for (int y = 0; y < imgHeight; y++) {
      for (int x = 0; x < imgWidth; x++) {
          float cx = (float)((x - halfWidth));
          float cy = (float)((y - halfHeight));
          float radiusSquared = sqrt((cx * cx) + (cy * cy));
          float f = (1) - (radiusSquared * (float)(i*3)/2000000);

          int newX = (int)(f * cx) + halfWidth;
          int newY = (int)(f * cy) + halfHeight;

          if (newX >= 0 && newY >= 0 && newX < imgWidth && newY < imgHeight) {
              *(newPixels + (y * imgWidth) + x) = *(oldPixels + (newY * imgWidth) + newX);
          }
          else{
            *(newPixels + (y * imgWidth) + x) = -1;
          }
      }
  }
  return new QPixmap(QPixmap::fromImage(warpedImage));
}


}//namepace
